import 'dart:async';

import 'package:flutter/material.dart';

class BannerWidget extends StatefulWidget {
  final List<String> imageList;
  final int seconds;

  const BannerWidget({super.key, required this.imageList, this.seconds = 5});

  @override
  State<StatefulWidget> createState() {
    return _BannerWidgetState();
  }
}

class _BannerWidgetState extends State<BannerWidget> {
  //当前展示的图片的索引
  int _currentIndex = 1;

  Timer? _timer;
  late PageController _pageController;
  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: 1000);
    _timer = Timer.periodic(Duration(seconds: widget.seconds), (timer) {
      //执行自动轮播
      if (_pageController.hasClients) {
        //获取当前page
        if (_pageController.page != null) {
          int page = _pageController.page!.round();
          //下一页
          int nextPage = page + 1;
          //
          _pageController.animateToPage(
            nextPage,
            duration: Duration(milliseconds: 400),
            curve: Curves.ease,
          );
        }
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();

    if (_timer != null) {
      _timer!.cancel();
      _timer = null;
    }
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned.fill(
          child: PageView.builder(
            controller: _pageController,
            itemCount: 10000,
            onPageChanged: (int index) {
              int autIndex = index % widget.imageList.length;
              _currentIndex = autIndex + 1;
              setState(() {});
            },
            itemBuilder: (BuildContext context, int index) {
              int autIndex = index % widget.imageList.length;
              return Image.asset(widget.imageList[autIndex], fit: BoxFit.cover);
            },
          ),
        ),
        Positioned(
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white.withValues(alpha: 0.5),
              borderRadius: BorderRadius.circular(10),
            ),
            padding: EdgeInsets.only(left: 6, right: 6),
            child: Text('$_currentIndex/${widget.imageList.length}'),
          ),
          bottom: 20,
          right: 20,
        ),
      ],
    );
  }
}
